package com.huiminpay.mq;

import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

@Component
public class ProducerSimple {
    @Autowired
    RocketMQTemplate rocketMQTemplate;

    /**
     * 同步消息
     * @param topic
     * @param msg
     */
    public void sendSyncMsg(String topic, String msg){
        SendResult sendResult = rocketMQTemplate.syncSend(topic, msg);
        System.out.println(sendResult);
    }

    /**
     * 异步消息
     * @param topic
     * @param msg
     */
    public void sendASyncMsg(String topic, String msg){
        rocketMQTemplate.asyncSend(topic,msg, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                System.out.println("发送成功"+sendResult);
            }

            @Override
            public void onException(Throwable throwable) {
                System.out.println("发送失败"+throwable.getMessage());
            }
        });
    }

    public void sendOneWayMsg(String topic, String msg){
        this.rocketMQTemplate.sendOneWay(topic,msg);
    }


    public void sendSyncMsg(String topic, OrderExt orderExt){
        rocketMQTemplate.convertAndSend(topic,orderExt);
    }


    public void sendMsgByJsonDelay(String topic, OrderExt orderExt){
        //发送同步消息，消息内容将orderExt转为json
        Message<OrderExt> message = MessageBuilder.withPayload(orderExt).build();


        rocketMQTemplate.syncSend(topic,message,3000,3);
    }
}
